package com.shop.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shop.entity.Order;
import com.shop.entity.OrderItem;
import com.shop.entity.Product;
import com.shop.mapper.OrderMapper;
import com.shop.mapper.ProductMapper;
import com.shop.service.OrderService;
import com.shop.service.vo.CartVo;
import com.shop.service.vo.OrderItemVo;
import com.shop.service.vo.OrderStatus;
import com.shop.service.vo.OrderVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author D
 * @since 2023-03-11 03:02:04
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {
    @Autowired
    RedisTemplate<String, Object> redisTemplate;
    @Autowired
    ProductMapper productMapper;

    @Override
    public OrderItemVo addOrder(Integer userId, Integer[] productIds) {
        HashOperations<String, Object, Object> opsForHash = redisTemplate.opsForHash();
        List<Object> cartList = Arrays.stream(productIds).map(productId -> {
            return opsForHash.get(userId.toString(), productId.toString());
        }).collect(Collectors.toList());
        OrderItemVo orderItemVo = new OrderItemVo();
        BigDecimal totalAmount = new BigDecimal(0);
        for (Object cart : cartList) {
            Product product = productMapper.selectById(((CartVo) cart).getProductId());
            CartVo cartVo = (CartVo) cart;

            OrderVo orderVo = new OrderVo();
            orderVo.setName(product.getProductName())
                    .setPrice(cartVo.getTotal())
                    .setCount(cartVo.getQuantity())
                    .setImgsrc(product.getProductImgsrc());
            totalAmount = totalAmount.add(cartVo.getTotal());
            orderItemVo.getOrderVo().add(orderVo);
        }
        orderItemVo.setCreatedTime(new Date())
                .setOrderNum("Woniu-" + System.currentTimeMillis())
                .setStatus(OrderStatus.UNPAY.getCode())
                .setTotalprice(totalAmount);
        redisTemplate.opsForHash().put(userId+"-Order", "order", orderItemVo);

        return orderItemVo;
    }

    @Override
    public OrderItemVo listOrders(Integer userId) {
        return (OrderItemVo) redisTemplate.opsForHash().get(userId+"-Order", "order");

    }
}
